package haha.life.normal;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jzqb.po.AdminKeyValuePo;
import jzqb.po.AdminTokenPo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtils {
//    @Value("${jwtToken.expire}")
//    private String expire;

    public static String generateToken(String id) {

        AdminTokenPo admintokenpo = new AdminTokenPo();
        admintokenpo.setId(id);
        String UserJson = CommonConvertUtils.getBeanToJson(admintokenpo);
        long now = System.currentTimeMillis();//当前时间
//        long exp = now + 1000 * 60*60;//过期时间单位:ms
        long exp = now + 1000 * 60 * 60 * 24;//过期时间单位:ms
        JwtBuilder builder = Jwts.builder()
                .setSubject(UserJson)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "secretKey")
                .setExpiration(new Date(exp));//用于设置过期时间
        String access_token = builder.compact();
        return access_token;

    }

    public static String checkTokenReturnID(String access_token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey("secretKey").parseClaimsJws(access_token).getBody();
        } catch (Exception e) {
            claims = null;
        }

        if (claims == null) {
            //过期或错误
            System.out.println("token过期或错误");
            return null;
        } else {
            String subject = claims.getSubject();
            AdminKeyValuePo AdminKeyValuePo = CommonConvertUtils.getJsonToBean(subject, AdminKeyValuePo.class);
            String ID = AdminKeyValuePo.getId();
            return ID;
        }
    }

    public static String getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        String currentUserId = TokenUtils.checkTokenReturnID(token);
        if ("".equals(currentUserId) || currentUserId == null) {
            currentUserId = "ANONY";
        }
        return currentUserId;
    }
}
